<template>
  <view class="container">
    <view class="title">欢迎使用我的小程序</view>
    <button type="primary" open-type="getUserProfile" @tap="getUserProfile">授权登录</button>
  </view>
</template>

<script>
export default {
  methods: {
    getUserProfile() {
      // 微信推荐接口
      uni.getUserProfile({
        desc: "用于完善用户资料",
        success: (res) => {
          console.log("用户信息:", res.userInfo);
          // 第一步：微信登录获取 code
          uni.login({
            provider: "weixin",
            success: (loginRes) => {
			  const code = loginRes.code;
              // 第二步：发到后端
              uni.request({
                url: `https://${this.$IP}:8443/api/wechat/login`,
                method: "GET",
                data: {code},
                success: (resp) => {
				  const openid = resp.data.openid;
				  uni.setStorageSync('openid', openid)
				  console.log(openid);
				  uni.redirectTo({
				    url: "/pages/index/index",
				  });
                },
              });
            },
          });
        },
        fail: () => {
          uni.showToast({
            title: "请授权登录后使用",
            icon: "none",
          });
        },
      });
    },
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.title {
  font-size: 22px;
  margin-bottom: 40px;
}
button {
  width: 200px;
}
</style>
